//
//  PersonPhoneViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/12.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "PersonPhoneViewController.h"
#import "ProtocolManager.h"
#import "Common.h"
#import "PersonViewController.h"
#import "SettingViewController.h"
#import "PersonManagerViewController.h"


@interface PersonPhoneViewController (){
    //UITableView *_tableView;
    CGRect rect;
    CGSize size;
    UITextField *_txtPhoneNumber;
    UITextField *_txtVerifyNumber;
    UIButton *btnGetVerifyNumber;
    NSString *verifyNumber;
    UIButton *btnConfirm;
}

@end

@implementation PersonPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
    NSLog(@"Loading PersonPhoneViewController;");
    
    rect = [UIScreen mainScreen].bounds;
    size = rect.size;
    [self initView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initView{
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"PhoneLoginView" owner:nil options:nil];
    self.view = [nibView objectAtIndex:0];
    //    UIButton *btnGoBack = [UIButton buttonWithType:UIButtonTypeSystem];
    //    btnGoBack.frame = CGRectMake(0, 25, 50, 30);
    //    [btnGoBack setTitle:@"取消" forState:UIControlStateNormal];
    //    [self.view addSubview:btnGoBack];
    //    [btnGoBack addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];
    
    _txtPhoneNumber = (UITextField *)[self.view viewWithTag:30001];
    //    _txtPhoneNumber = [[UITextField alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(btnGoBack.frame) + 20, size.width - 100, 30)];
    //    _txtPhoneNumber.placeholder = @"请输入手机号";
    //    _txtPhoneNumber.borderStyle = UITextBorderStyleRoundedRect;
    //    [self.view addSubview:_txtPhoneNumber];
    
    //    btnGetVerifyNumber = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    //    btnGetVerifyNumber.frame = CGRectMake(CGRectGetMaxX(_txtPhoneNumber.frame) + 5, CGRectGetMaxY(btnGoBack.frame) + 20, size.width - (CGRectGetMaxX(_txtPhoneNumber.frame) + 5), 30);
    //    [btnGetVerifyNumber setTitle:@"获取验证码" forState:UIControlStateNormal];
    btnGetVerifyNumber = (UIButton *)[self.view viewWithTag:30003];
    [btnGetVerifyNumber addTarget:self action:@selector(getVerifyNumberAction) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:btnGetVerifyNumber];
    
    _txtVerifyNumber = (UITextField *)[self.view viewWithTag:30002];
    //    _txtVerifyNumber = [[UITextField alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(_txtPhoneNumber.frame) + 20, size.width - 10, 30)];
    //    _txtVerifyNumber.placeholder = @"请输入短信中的验证码";
    //    _txtVerifyNumber.borderStyle = UITextBorderStyleRoundedRect;
    //    [self.view addSubview:_txtVerifyNumber];
    
    //    UIButton *btnConfirm = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    //    btnConfirm.frame = CGRectMake(5, CGRectGetMaxY(_txtVerifyNumber.frame) + 20, size.width - 10, 30);
    //    [btnConfirm setTitle:@"登录" forState:UIControlStateNormal];
    btnConfirm = (UIButton *)[self.view viewWithTag:30004];
    [btnConfirm addTarget:self action:@selector(doConfirmAction) forControlEvents:UIControlEventTouchUpInside];
    [btnConfirm setTitle:@"验证并绑定" forState:UIControlStateNormal];
    //    [self.view addSubview:btnConfirm];
}

- (void)goBackAction{
    //[theTimer invalidate];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getVerifyNumberAction{
    NSLog(@"%s || getVerifyNumberAction's been actived.", __FUNCTION__);
    if([_txtPhoneNumber.text isEqualToString:@""] || [_txtPhoneNumber.text length] != 11){
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"请输入正确的手机号码！" dismissTime:1.2];
        return;
    }else{
//        btnGetVerifyNumber.enabled = NO;
//        [[Common shareInstance] showAlertViewWithTitle:nil text:@"短信已发送" dismissTime:0.8];
        [[ProtocolManager shareInstance] mobileValidationWithMobile:_txtPhoneNumber.text target:self selector:@selector(mobileValidationCallback:)];
        [self startTime];
    }
}

- (void)mobileValidationCallback:(NSDictionary*)dic
{
    NSLog(@"%s || mobileValidationCallback %@", __FUNCTION__, dic)
    if (dic == nil) {
        return;
    }
    //verifyNumber = [Common valueForKey:P_CODE dic:dic];
    if([[dic objectForKey:P_RESPCODE] isEqualToString:@"000"]){
        
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"短信发送成功" dismissTime:0.8];
        verifyNumber = [[NSString alloc]initWithFormat:@"%@",[Common valueForKey:P_CODE dic:dic]];
        NSLog(@"%s || verifyNumber:%@", __FUNCTION__, verifyNumber);
    }else if([[Common valueForKey:@"respCode" dic:dic]isEqualToString:@"007"]){
//        [[Common shareInstance]stopLoadingView];
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"该手机号已被使用！" dismissTime:1.2];
    }
    [[Common shareInstance]stopLoadingView];
}

- (void)doConfirmAction{
    NSString *tempString = _txtVerifyNumber.text;
    NSLog(@"%s || tempString:%@", __FUNCTION__, tempString);
    if([tempString isEqualToString:verifyNumber]){
        NSLog(@"%s || verifyNumber's correct!", __FUNCTION__);
        [[Common shareInstance]showLoadingViewWithMessage:nil];
        [[ProtocolManager shareInstance] mobileBinding:[ProtocolManager shareInstance].loginName mobile:_txtPhoneNumber.text target:self selector:@selector(getBindingActionCallBack:)];
    }else{
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"请校验验证码是否正确！" dismissTime:1.2];
    }
}

- (void)getBindingActionCallBack:(NSDictionary *)dic{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic)
    if (dic == nil) {
        return;
    }
    if([[dic objectForKey:P_RESPCODE] isEqualToString:@"000"]){
        [[NSUserDefaults standardUserDefaults] setObject:_txtPhoneNumber.text forKey:P_MOBILE];
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"绑定成功！" dismissTime:1.2];
        [self.delegate changePhoneAfterVerifying:_txtPhoneNumber.text];
    }

//    [self dismissViewControllerAnimated:YES completion:nil];
    [[Common shareInstance]stopLoadingView];
    [self.navigationController popViewControllerAnimated:YES];
}
//
-(void)startTime{
    __block int timeout=30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [btnGetVerifyNumber setTitle:@"获取验证码" forState:UIControlStateNormal];
                btnGetVerifyNumber.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [btnGetVerifyNumber setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                btnGetVerifyNumber.userInteractionEnabled = NO;
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}


@end
